import { defineStore } from 'pinia'
import { accountLoginRequest, getUserInfoById, getUserMenuByRoleId } from '@/service/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menus'
import { LOGIN_TOKEN } from '@/global/constants'
import router from '@/router'
import useMainStore from './main'

interface ILoginState {
  token: string
  // 如果返回的数据类型复杂，可直接使用any
  userInfo: any
  userMenus: any
}

const useLoginStore = defineStore('login', {
  // 如何指定state的类型：指定箭头函数返回值类型
  state: (): ILoginState => ({
    // token: localCache.getCache(LOGIN_TOKEN) ?? '',
    // userInfo: localCache.getCache('userInfo') ?? {},
    // userMenus: localCache.getCache('userMenus') ?? []
    token: '',
    userInfo: {},
    userMenus: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      const loginResult = await accountLoginRequest(account)
      // console.log(loginResult)
      const id = loginResult.data.id
      this.token = loginResult.data.token
      localCache.setCache(LOGIN_TOKEN, this.token)
      // 获取用户的详细信息（role信息），用于加载不同角色的菜单
      const userResult = await getUserInfoById(id)
      // console.log(userResult)
      const userInfo = userResult.data
      this.userInfo = userInfo
      // console.log(this.userInfo.role)
      // 请求不同用户的菜单权限
      const userMenusResult = await getUserMenuByRoleId(this.userInfo.role.id)
      // console.log(userMenusResult.data)
      const userMenus = userMenusResult.data
      this.userMenus = userMenus
      // console.log(userMenus)
      // 数据缓存
      localCache.setCache('userInfo', userInfo)
      localCache.setCache('userMenus', userMenus)

      // 请求所有role/departments数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()

      // 重要：根据不同的登录用户，动态添加路由
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => router.addRoute('main', route))

      // 登录成功，页面跳转
      router.push('/main')
    },
    loadLocalCacheAction() {
      // 用户刷新默认加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if(token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 请求所有role/departments数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 重要：根据不同的登录用户，动态添加路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})
export default useLoginStore
